//
//  KLSettingViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BBSettingViewController.h"
#import "STPhotoUrlImageBrowerController.h"
#import "BBChangePwdViewController.h"
@interface BBSettingViewController ()<STPhotoUrlImageBrowerControllerDelegate,STActionSheetDelegate>
@property(nonatomic, strong) NSArray  <STTableEasyModel*>                   *dataSouce;
@property(nonatomic, strong) STButton                     *iconButton;
@property(nonatomic, strong) UISwitch                     *messageSwitch;
@property(nonatomic, strong) STPhotoUrlImageBrowerController                     *pickerVC;
@property(nonatomic, strong) STUrlPhotoModel                     *imageModel;

@end

@implementation BBSettingViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"账号管理";
    [self configSubView];
    [self reloadData];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.userModel) {
        [self sendMyInfoRequest];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:20
                                      backgroundColor:nil
                                      backgroundImage:[UIImage imageNamed:@"个人头像"]
                                                image:nil];
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconCell];
    }];
    [self.iconButton st_setBorderWith:1 borderColor:UIColor.whiteColor cornerRadius:20];
    [self configTableFooter];
}
- (void)configTableFooter{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth , 44)
                                                        title:@"退出登录"
                                                   titleColor:[BBThemeColorManger manger].firstTextColor
                                                    titleFont:18
                                                 cornerRadius:0
                                              backgroundColor:[UIColor whiteColor]
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLogoutButton];
    }];
    confimButton.st_centerY = 50;
    [confimButton st_showTopLine];
    [confimButton st_showBottomLine];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
    
    if (BBThemeColorManger.isBlack) {
        confimButton.backgroundColor = [BBThemeColorManger manger].backGroundColor;
        [confimButton st_setBorderWith:1 borderColor:UIColor.whiteColor cornerRadius:0];
    }
}
- (void)reloadData{
    
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    STTableEasyModel * versionModel = [[STTableEasyModel alloc] initWithTextString:@"当前版本"
                                                                      detailString:[NSString stringWithFormat:@"v%@",version]];
    versionModel.accessoryType = UITableViewCellAccessoryNone;
    [self.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:self.userModel.avatar] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"个人头像"]];
    NSString * nickName = self.userModel.nickname;
    NSArray * sectionOne = @[
                             [[STTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[STTableEasyModel alloc] initWithTextString:@"昵称" detailString:nickName],
                              [[STTableEasyModel alloc] initWithTextString:@"我的积分"
                                                              detailString:self.userModel.coin.description],
                             [[STTableEasyModel alloc] initWithTextString:@"修改密码" detailString:@""]
                            ];
    
    
    self.dataSouce = sectionOne;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if ([model.textString isEqualToString:@"头像"]) {
        model.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.accessoryType = model.accessoryType;
    }
    if (BBThemeColorManger.isBlack) {
        cell.backgroundColor = [BBThemeColorManger manger].backGroundColor;
        cell.textLabel.textColor = UIColor.whiteColor;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if ([model.textString isEqualToString:@"昵称"]) {
          [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"头像"]) {
        [self onSelectedIconCell];
    }

    if ([model.textString isEqualToString:@"修改密码"]) {
        [self.navigationController pushViewController:[BBChangePwdViewController new] animated:YES];
    }

    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)onSelectedIconCell{
    STUrlPhotoModel * model = [STUrlPhotoModel new];
    model.thumbImage = self.iconButton.currentBackgroundImage;
    if (self.userModel) {
        model.thumbImageUrl = self.userModel.avatar;
    }
    self.imageModel = model;
    self.pickerVC = [[STPhotoUrlImageBrowerController alloc] initWithArray:@[model] curentIndex:0];
    self.pickerVC.STPhotoUrlImageBrowerControllerdelegate = self;
    self.pickerVC.themeColor = TM_ThemeBackGroundColor;
    [self presentViewController:self.pickerVC animated:NO completion:nil];
}
- (void)onSelectedNickNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popToRootViewControllerAnimated:YES];
                                                      }];
    
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
    
    STActionSheet * actionSheet = [[STActionSheet alloc] initWithTitle:nil
                                                          buttonTitles:@[@"拍照",@"从手机相册选择",@"保存图片"] cancelTitle:@"取消"
                                                              delegate:self
                                   ];
    [actionSheet show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.pickerVC showTakePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 1) {
        [self.pickerVC showchosePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 2) {
        [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage
                                     libraryName:@"区块链浏览器" successHandle:^{
                                         [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
                                     } errorHandle:^(STSaveImageError error) {
                                         
                                     }];
    }
}
#pragma mark --Action Method
- (void)onSelectedLogoutButton{
    [self showAlertCancelAndConfirm:@"确定要退出登录吗?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [[STUserManger defult] removeUserPreferce];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
    
}
#pragma mark --NetWork Method
- (void)sendChangeNickNameRequest:(NSString*)nickName withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/user/editInfo?=&name=nickname&"];
    if (nickName.length) {
        NSString * encodingString = [nickName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        url = [NSString stringWithFormat:@"%@content=%@",url,encodingString];
    }
    

   // url = @"http://www.zipengdp.cn/api/user/editInfo?=&name=nickname&content=dasdasd";
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:nil
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = nickName;
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendIconChangeRequest:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20;

    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/file/upload/pictureUpload"];

    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        long long time = [[NSDate date] timeIntervalSince1970]* 1000;
        [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5)
                                    name:@"file"
                                fileName:[NSString stringWithFormat:@"%lld.png",time] mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSString * url = responseObject[@"message"];
        [self sendIconUrlChangedRequestWithFace:url image:image];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"修改头像失败"];
    }];


}
- (void)sendIconUrlChangedRequestWithFace:(NSString*)face image:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/user/editInfo"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [dic setObject:@"avatar" forKey:@"name"];
    if (face.length) {
        [dic setObject:face forKey:@"content"];
    }

    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 //NSString * dataStr =  responseObject[@"data"];
                                                 [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                 self.imageModel.originImage = image;
                                                 [self.pickerVC reloadData];
                                                 [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendMyInfoRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/advert/list"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.userModel = [BBUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

